const { sys_log_model: SysLogModel, sys_user_model: SysUserModel } = require('../models');
const DateUtils = require('../utils/dateUtils');
const { Op } = require('sequelize');
const { realDelete } = require('../config/system');

class LogService {
    /**
     * 创建系统日志
     * @param {Object} logData 日志数据
     * @returns {Promise<Object>} 创建的日志对象
     */
    async createLog(logData) {
        return await SysLogModel.create(logData);
    }

    /**
     * 获取访问趋势统计
     * @param {string} startDate 开始日期
     * @param {string} endDate 结束日期
     * @returns {Promise<Array>} 访问趋势数据
     */
    async getVisitTrend(startDate, endDate) {
        // 查询指定时间范围内的日志数据
        const logs = await SysLogModel.findAll({
            where: {
                create_time: {
                    [Op.between]: [startDate, endDate]
                }
            },
            attributes: ['ip', 'create_time']
        });

        // 按日期分组统计
        const dailyStats = {};
        logs.forEach(log => {
            const date = DateUtils.formatDate(log.create_time);
            if (!dailyStats[date]) {
                dailyStats[date] = {
                    date,
                    pv: 0,
                    uniqueIps: new Set()
                };
            }
            dailyStats[date].pv++;
            dailyStats[date].uniqueIps.add(log.ip);
        });

        // 转换为所需的数据格式
        const sortedDates = Object.keys(dailyStats).sort();
        const result = {
            dates: sortedDates,
            pvList: sortedDates.map(date => dailyStats[date].pv),
            ipList: sortedDates.map(date => dailyStats[date].uniqueIps.size)
        };

        return result;
    }

    /**
     * 删除系统日志
     * @param {number} id 日志ID
     */
    async deleteLog(id) {
        const log = await SysLogModel.findByPk(id);
        if (!log) {
            throw new Error('日志数据不存在');
        }
        if (realDelete) {
            // 真实删除
            await log.destroy();
        } else {
            // 软删除
            await log.update({
                is_deleted: 1,
                update_time: DateUtils.getCurrentTime()
            });
        }
    }

    async batchDeleteLog(ids) {
        if (realDelete) {
            // 真实删除
            await SysLogModel.destroy({
                where: { id: { [Op.in]: ids } }
            });
        } else {
            // 软删除
            await SysLogModel.update(
                { 
                    is_deleted: 1,
                    update_time: DateUtils.getCurrentTime()
                },
                { where: { id: { [Op.in]: ids }, is_deleted: 0 } }
            );
        }
    }

    /**
     * 清空系统日志
     */
    async clearLog() {
        if (realDelete) {
            // 真实删除
            await SysLogModel.destroy({
                where: {},  // 或者 truncate: true
            });
        } else {
            // 软删除
            await SysLogModel.update(
                { 
                    is_deleted: 1,
                    update_time: DateUtils.getCurrentTime()
                },
                { where: { is_deleted: 0 } }
            );
        }
    }

    /**
     * 获取系统日志详情
     * @param {number} id 日志ID
     */
    async getLogById(id) {
        return await SysLogModel.findOne({
            where: { id, isDeleted: 0 }
        });
    }

    /**
     * 获取系统日志列表
     * @param {Object} query 查询条件
     */
    async getLogList(query) {
        const { module, requestMethod, keywords, ip, createTime, pageNum = 1, pageSize = 10 } = query;
        const where = { isDeleted: 0 };

        if (module) {
            where.module = { [Op.like]: `%${module}%` };
        }
        if (requestMethod) {
            where.requestMethod = requestMethod;
        }
        if (keywords) {
            where.content = { [Op.like]: `%${keywords}%` };
        }
        if (ip) {
            where.ip = { [Op.like]: `%${ip}%` };
        }
        if (createTime && Array.isArray(createTime) && createTime.length === 2 && createTime[0] && createTime[1]) {
            where.createTime = {
                [Op.between]: [createTime[0], createTime[1]]
            };
        }

        const { rows, count } = await SysLogModel.findAndCountAll({
            where,
            offset: (pageNum - 1) * pageSize,
            limit: parseInt(pageSize),
            order: [['create_time', 'DESC']],
            include: [{
                model: SysUserModel,
                as: 'creator',
                attributes: ['username'],
                required: false
            }]
        });

        // 格式化返回结果，添加创建人用户名
        const formattedRows = rows.map(row => {
            const plainRow = row.get({ plain: true });
            return {
                ...plainRow,
                operator: plainRow.creator ? plainRow.creator.username : null
            };
        });

        return {
            rows: formattedRows,
            count
        };
    }
}

module.exports = new LogService();